//
//  CMRequest.swift
//  SwiftDemo
//
//  Created by mac on 2020/4/27.
//  Copyright © 2020 yimiSun. All rights reserved.
//

import Foundation
import Alamofire
import SVProgressHUD

/**
 * 网络请求
 * Alamofire 5 的使用 - 基本用法
 * https://www.jianshu.com/p/4381fe8e10b6
 */
struct CMRequest {
    
    typealias SuccessBlock = (_ responseData:Any?) -> (Void)
    typealias FailureBlock = (_ responseString:String?) -> (Void)
    
    private static let _request = CMRequest.init()
    static func shareInstance() -> CMRequest {
        return _request
    }
    
    
    //MARK: - errorHandle
    private func errorHandle(Error e:NSError?,
                             statusCode:Int?,
                             andErrormsg ems:inout String?) {
        let code:Int? = e?.code
        print("error code:\(code ?? 0)")
        
        //https://www.jb51.net/article/105163.htm
        switch statusCode {
        case .some(302):
            ems = "请求被重定向"
            
        case .some(400):
            ems = "发送的请求有语法错误"
            
        case .some(401):
            ems = "访问没有授权"
            
        case .some(403):
            ems = "没有权限访问"
           
        case .some(404):
            ems = "请求地址不存在"
            
        case .some(405):
            ems = "请求方式不存在"
            
        case .some(408),.some(504):
            ems = "请求超时,请检查网络或重试"
            
        case .some(500):
            ems = "服务器内部异常,无法完成请求处理"
            
        case .some(507):
            ems = "服务器无法存储完成请求所必须的内容"
            
        case .some(509):
            ems = "服务器达到带宽限制"
            
        case .some(510):
            ems = "获取资源所需要的策略并没有没满足"
            
        default:
            break
        }
        
        switch code {
        case .some(-1001):
            ems = "请求超时"
            
        //token 过期
        case .some(-1011),.some(3),.some(9):
            
            if statusCode == 400 || (statusCode == 401 && UserModel.userDicData == nil)  {
                ems = "用户名或密码错误"
            }
            else if statusCode == 401 {
                ems = "用户名或密码错误"
                let vc = UIApplication.shared.keyWindow!.rootViewController
                
                Utils.shareInstance().showBoxFor(ViewController: vc!,
                           andMessage: "您的账号可能在别处登录,请重新登录",
                           andOK: "去登录",
                           andOKImport: false,
                           andOKBlock: {(action:UIAlertAction) in
                            
                            let login = LoginViewController()
                            login.modalPresentationStyle = .fullScreen
                            login.modalTransitionStyle = .flipHorizontal
                            vc?.present(login, animated: true, completion: nil)
                },
                           andCancle: "取消",
                           withType: .alert)
            }
            
        case .some(-32700):
            ems = "类型转换错误"
            
        case .some(-32600):
            ems = "无效的请求"
            
        case .some(-32601):
            ems = "没有找到方法"
            
        case .some(-32602):
            ems = "无效的参数"
            
        case .some(-32603),.some(-1009):
            ems = "网络异常，请检查网络"
            
        default:
            break
        }
    }
    
    
    //MARK: -
    ///  OAuth Password 网络请求
    ///  https://github.com/AFNetworking/AFOAuth2Manager
    /// - Parameters:
    ///   - un: 用户名
    ///   - pwd: 密码
    ///   - successBack: 成功回调
    ///   - failureBack: 失败回调
    ///   - isLoading: 是否显示加载
    func oAuthRequestPasswordFor(Username un:String,
                                 andPwd pwd:String,
                                 andSuccessBack successBack:@escaping SuccessBlock,
                                 andFailureBack failureBack:@escaping FailureBlock,
                                 withisLoading isLoading:Bool = true){
        
        let strUrl = String.init(format:"%@oauth/token",K_APP_OAUTH_HOST)
        print("请求地址：\(strUrl),参数：\(un),\(pwd)")

        if isLoading == true {
           SVProgressHUD.showLoading()
        }
        
        let dicParam = [
            "username": un,
            "password": pwd,
            "grant_type":"password",
            "client_id":K_APP_IS_PRODUCT ? K_APP_CLIENT_ID_PRO : K_APP_CLIENT_ID_DEV,
            "client_secret":K_APP_IS_PRODUCT ? K_APP_CLIENT_SECRET_PRO : K_APP_CLIENT_SECRET_DEV
        ]
        
        AF.request(strUrl,
                          method: .post,
                      parameters: dicParam)
                 .validate()
                 .responseJSON { response in

                    if isLoading == true {
                        SVProgressHUD.dismissLoading()
                    }
                    
                    var msg:String? = response.error?.localizedDescription ?? ""
                    self.errorHandle(Error: response.error as NSError?,
                                     statusCode: response.response?.statusCode,
                                     andErrormsg: &msg)
                    
                    print("请求结果：\(response)")
                    if response.error != nil {
                        failureBack(msg)
                    }
                    else{
                        if let jsonObj:[String:Any] = response.value as? [String:Any] {
                            let access_token:String? = jsonObj[UserModel.k_user_tooken] as? String
                            if access_token == nil || access_token == "" {
                                failureBack("用户名或密码错误")
                            }
                            else{
                                //请求成功
                                successBack(access_token)
                            }
                        }
                        else{
                            failureBack("请求token不存在")
                        }
                    }
        }
    }
    
    
    /// GET请求
    /// - Parameters:
    ///   - strUrl: 请求地址
    ///   - paras: 请求参数
    ///   - successBack: 成功回调
    ///   - failureBack: 失败回到
    ///   - isLoading: 是否加载动画
    func getRequestForServerData(strUrl:String,
                                 withParameters paras:[String:Any]?,
                                 AndSuccessBack successBack:@escaping SuccessBlock,
                                 AndFailureBack failureBack:@escaping FailureBlock,
                                 WithisLoading isLoading:Bool = true){
        
        if paras != nil {
            print("请求地址：\(strUrl)?\(paras!.map({ return "\($0.key)=\($0.value)"}).joined(separator: "&"))")
        }
        else{
            print("请求地址：\(strUrl)")
        }
        
        if isLoading == true {
            SVProgressHUD.showLoading()
        }

        AF.request(strUrl,
                          method: .get,
                          parameters: paras)
                .validate()
                .validate(contentType: K_APP_ACCEPTABLE_CONTENTTYPES)
                .responseJSON { response in
            
            if isLoading == true {
                SVProgressHUD.dismissLoading()
            }
            
            var msg:String? = response.error?.localizedDescription ?? ""
            self.errorHandle(Error: response.error as NSError?,
                             statusCode: response.response?.statusCode,
                             andErrormsg: &msg)
                    
            print("请求结果：\(response)")
            if response.error != nil {
                failureBack(msg)
            }
            else{
                if let jsonObj:[String:Any] = response.value as? [String:Any] {
                     //请求成功
                     if K_API_IS_OK(rs: jsonObj[K_API_RESULT_CODE]) || jsonObj[K_API_RESULT_CODE] as? Int == 200 {
                         successBack(jsonObj[K_API_RESULT_DATA] is NSNull ? Any.self : jsonObj[K_API_RESULT_DATA])
                     }
                     //获取用户信息
                     else if let _dicTemp = jsonObj["userAuthentication"] as? [String:Any] {
                         successBack(_dicTemp)
                     }
                     else{
                        failureBack("\(jsonObj[K_API_RESULT_MESSAGE] ?? "请求失败")")
                    }
                }
                else{
                    failureBack(msg)
                }
            }
         }
    }
    
    
    /// GET请求2
    /// - Parameters:
    ///   - strUrl: 请求地址
    ///   - paras: 请求参数
    ///   - successBack: 成功回调
    ///   - failureBack: 失败回到
    ///   - isLoading: 是否加载动画
    func getRequestForServerData2(strUrl:String,
                                 withParameters paras:[String:Any]?,
                                 AndSuccessBack successBack:@escaping SuccessBlock,
                                 AndFailureBack failureBack:@escaping FailureBlock,
                                 WithisLoading isLoading:Bool = true){
        
        if paras != nil {
            print("请求地址：\(strUrl)?\(paras!.map({ return "\($0.key)=\($0.value)"}).joined(separator: "&"))")
        }
        else{
            print("请求地址：\(strUrl)")
        }
        
        if isLoading == true {
            SVProgressHUD.showLoading()
        }

        AF.request(strUrl,
                          method: .get,
                          parameters: paras)
                .validate()
                .validate(contentType: K_APP_ACCEPTABLE_CONTENTTYPES)
                .responseJSON { response in
            
            if isLoading == true {
                SVProgressHUD.dismissLoading()
            }
            
            var msg:String? = response.error?.localizedDescription ?? ""
            self.errorHandle(Error: response.error as NSError?,
                             statusCode: response.response?.statusCode,
                             andErrormsg: &msg)
                    
            print("请求结果：\(response)")
            if response.error != nil {
                failureBack(msg)
            }
            else{
                if let jsonObj:[String:Any] = response.value as? [String:Any] {
                    //请求成功
                    if K_API_IS_OK(rs: jsonObj[K_API_RESULT_CODE]) || jsonObj[K_API_RESULT_CODE] as? Int == 200 {
                        let data = (jsonObj[K_API_RESULT_DATA] is NSNull ? Any.self : jsonObj[K_API_RESULT_DATA],jsonObj[K_API_RESULT_COUNT])
                        successBack(data)
                    }
                    else{
                       failureBack("\(jsonObj[K_API_RESULT_MESSAGE] ?? "请求失败")")
                   }
                }
                else{
                    failureBack(msg)
                }
            }
         }
    }
    
    
    /// post 接口请求
    /// - Parameter strUrl: 请求地址
    /// - Parameter paras: 请求参数
    /// - Parameter headers: 请求头
    /// - Parameter successBack: 成功回调
    /// - Parameter failureBack: 失败回调
    /// - Parameter isLoading: 是否加载动画
    func postRequestWithParamsFor(strUrl:String,
                                  withParameters paras:[String:Any],
                                  AndRequestHeaders _headers:HTTPHeaders?,
                                  AndSuccessBack successBack:@escaping SuccessBlock,
                                  AndFailureBack failureBack:@escaping FailureBlock,
                                  WithisLoading isLoading:Bool = true){
        
        print("请求地址：\(strUrl)?\(paras.map({ return "\($0.key)=\($0.value)"}).joined(separator: "&"))")
        
        if isLoading == true {
            SVProgressHUD.showLoading()
        }
        
        AF.request(strUrl,
                          method: .post,
                          parameters: paras,
                          headers: _headers)
                 .validate()
                 .validate(contentType: K_APP_ACCEPTABLE_CONTENTTYPES)
                 .responseJSON { response in

                   if isLoading == true {
                       SVProgressHUD.dismissLoading()
                   }

                   var msg:String? = response.error?.localizedDescription ?? ""
                   self.errorHandle(Error: response.error as NSError?,
                              statusCode: response.response?.statusCode,
                             andErrormsg: &msg)
                    
                   print("请求结果：\(response)")
                   if response.error != nil {
                       failureBack(msg)
                   }
                   else{
                       if let jsonObj:[String:Any] = response.value as? [String:Any] {
                           //请求成功
                           if K_API_IS_OK(rs: jsonObj[K_API_RESULT_CODE]) || jsonObj[K_API_RESULT_CODE] as? Int == 200 {
                              successBack(jsonObj[K_API_RESULT_DATA] is NSNull ? Any.self : jsonObj[K_API_RESULT_DATA])
                           }
                           else{
                              failureBack("\(jsonObj[K_API_RESULT_MESSAGE] ?? "请求失败")")
                          }
                       }
                       else{
                           failureBack(msg)
                       }
                   }
        }
    }
    
    
    /**!
     * post 接口请求
     * @para strUrl   String 请求地址
     * @para body     Data? 请求参数
     * @para successBack  成功回调
     * @para failureBack  失败回调
     */
    func postRequestWithBodyFor(strUrl:String,
                                withBody body:Data?,
                                AndSuccessBack successBack:@escaping SuccessBlock,
                                AndFailureBack failureBack:@escaping FailureBlock,
                                WithisLoading isLoading:Bool = true) {
        
        if body != nil {
             print("请求地址：\(strUrl),参数：\(NSString.init(data: body!, encoding: String.Encoding.utf8.rawValue) ?? "暂无参数")")
        }
        else{
            print("请求地址：\(strUrl),暂无参数")
        }

        if isLoading == true {
            SVProgressHUD.showLoading()
        }
        
        var request = URLRequest.init(url: URL.init(string: strUrl)!)
        request.httpBody = body
        request.httpMethod = "POST"
        request.timeoutInterval = K_APP_REQUEST_TIME_OUT
        request.setValue("application/json", forHTTPHeaderField: "Accept")
        request.setValue("application/json;charset=UTF-8", forHTTPHeaderField: "Content-Type")
        
        AF.request(request)
                 .validate()
                 .validate(contentType: K_APP_ACCEPTABLE_CONTENTTYPES)
                 .responseJSON { response in
                
                      if isLoading == true {
                         SVProgressHUD.dismissLoading()
                      }

                      var msg:String? = response.error?.localizedDescription ?? ""
                      self.errorHandle(Error: response.error as NSError?,
                                  statusCode: response.response?.statusCode,
                                 andErrormsg: &msg)
                      
                      print("请求结果：\(response)")
                      if response.error != nil {
                         failureBack(msg)
                      }
                      else{
                        if let jsonObj:[String:Any] = response.value as? [String:Any] {
                            
                            var code:Int? = jsonObj[K_API_RESULT_CODE] as? Int
                            if code == nil, let strTemp = jsonObj[K_API_RESULT_CODE] as? String {
                                code = NSNumber.init(string:strTemp)?.intValue
                            }
                            
                            //请求成功
                            if K_API_IS_OK(rs: code) {
                                successBack(jsonObj[K_API_RESULT_DATA] is NSNull ? nil : jsonObj[K_API_RESULT_DATA])
                            }
                            //京东AI拍照识别
                            else if code == 10000 {
                                successBack(jsonObj["result"] is NSNull ? nil : jsonObj["result"])
                            }
                            else if code == 200 {
                                successBack(jsonObj[K_API_RESULT_DATA] is NSNull ? nil : jsonObj[K_API_RESULT_DATA])
                            }
                            else{
                               failureBack("\(jsonObj[K_API_RESULT_MESSAGE] ?? "请求失败")")
                           }
                        }
                        else{
                            failureBack(msg)
                        }
                    }
        }
    }
    
    
    /**!
     * put 接口请求
     * @para strUrl   String 请求地址
     * @para paras    [String:Any] 请求参数
     * @para successBack  成功回调
     * @para failureBack  失败回调
     */
    func putRequestForServerData(strUrl:String,
                                 withParameters paras:[String:Any]?,
                                 AndSuccessBack successBack:@escaping SuccessBlock,
                                 AndFailureBack failureBack:@escaping FailureBlock,
                                 WithisLoading isLoading:Bool = true){
        
        if paras != nil {
            print("请求地址：\(strUrl)?\(paras!.map({ return "\($0.key)=\($0.value)"}).joined(separator: "&"))")
        }
        else{
            print("请求地址：\(strUrl)")
        }
        
        if isLoading == true {
           SVProgressHUD.showLoading()
        }
        
        AF.request(strUrl,
                  method: .put,
                  parameters: paras)
           .validate()
           .validate(contentType: K_APP_ACCEPTABLE_CONTENTTYPES)
           .responseJSON { response in
           
           if isLoading == true {
               SVProgressHUD.dismissLoading()
           }
          
           var msg:String? = response.error?.localizedDescription ?? ""
           self.errorHandle(Error: response.error as NSError?,
                       statusCode: response.response?.statusCode,
                      andErrormsg: &msg)
            
           print("请求结果：\(response)")
           if response.error != nil {
               failureBack(msg)
           }
           else{
               if let jsonObj:[String:Any] = response.value as? [String:Any] {
                   //请求成功
                   if K_API_IS_OK(rs: jsonObj[K_API_RESULT_CODE]) || jsonObj[K_API_RESULT_CODE] as? Int == 200 {
                       successBack(jsonObj[K_API_RESULT_DATA] is NSNull ? Any.self : jsonObj[K_API_RESULT_DATA])
                   }
                   else{
                      failureBack("\(jsonObj[K_API_RESULT_MESSAGE] ?? "请求失败")")
                   }
               }
               else{
                   failureBack(msg)
               }
           }
        }
    }
    
    
    /**!
     * put 接口请求
     * @para strUrl   String 请求地址
     * @para body     Data 请求参数
     * @para successBack  成功回调
     * @para failureBack  失败回调
     */
    func putRequestWithBodyFor(strUrl:String,
                               withBody body:Data?,
                               AndSuccessBack successBack:@escaping SuccessBlock,
                               AndFailureBack failureBack:@escaping FailureBlock,
                               WithisLoading isLoading:Bool = true) {
        
        print("请求地址：\(strUrl),参数：\(NSString.init(data: body!, encoding: String.Encoding.utf8.rawValue) ?? "暂无参数")")
               
        if isLoading == true {
          SVProgressHUD.showLoading()
        }
        
        var request = URLRequest.init(url: URL.init(string: strUrl)!)
        request.httpBody = body
        request.httpMethod = "PUT"
        request.timeoutInterval = K_APP_REQUEST_TIME_OUT
        request.setValue("application/json", forHTTPHeaderField: "Accept")
        request.setValue("application/json;charset=UTF-8", forHTTPHeaderField: "Content-Type")
        
        AF.request(request)
                  .validate()
                  .validate(contentType: K_APP_ACCEPTABLE_CONTENTTYPES)
                  .responseJSON { response in

                   if isLoading == true {
                       SVProgressHUD.dismissLoading()
                   }

                   var msg:String? = response.error?.localizedDescription ?? ""
                   self.errorHandle(Error: response.error as NSError?,
                               statusCode: response.response?.statusCode,
                              andErrormsg: &msg)
                    
                   print("请求结果：\(response)")
                   if response.error != nil {
                       failureBack(msg)
                   }
                   else{
                       if let jsonObj:[String:Any] = response.value as? [String:Any] {
                           //请求成功
                           if K_API_IS_OK(rs: jsonObj[K_API_RESULT_CODE]) || jsonObj[K_API_RESULT_CODE] as? Int == 200 {
                               successBack(jsonObj[K_API_RESULT_DATA] is NSNull ? Any.self : jsonObj[K_API_RESULT_DATA])
                           }
                           else{
                              failureBack("\(jsonObj[K_API_RESULT_MESSAGE] ?? "请求失败")")
                          }
                       }
                       else{
                           failureBack(msg)
                       }
                   }
                }
    }
    
    
    /**!
     * delete 接口请求
     * @para strUrl   String 请求地址
     * @para body    Data? 请求参数
     * @para successBack  成功回调
     * @para failureBack  失败回调
     */
    func deleteRequestForServerData(strUrl:String,
                                    withBody body:[String:Any]?,
                                    AndSuccessBack successBack:@escaping SuccessBlock,
                                    AndFailureBack failureBack:@escaping FailureBlock,
                                    WithisLoading isLoading:Bool = true){
        
        if body != nil {
            print("请求地址：\(strUrl)?\(body!.map({ return "\($0.key)=\($0.value)"}).joined(separator: "&"))")
        }
        else{
            print("请求地址：\(strUrl)")
        }
        
        if isLoading == true {
           SVProgressHUD.showLoading()
        }
        
        AF.request(strUrl,
                   method: .delete,
                   parameters: body,
                   encoding: URLEncoding.httpBody)
          .validate()
          .validate(contentType: K_APP_ACCEPTABLE_CONTENTTYPES)
          .responseJSON { response in

           if isLoading == true {
               SVProgressHUD.dismissLoading()
           }

           var msg:String? = response.error?.localizedDescription ?? ""
           self.errorHandle(Error: response.error as NSError?,
                       statusCode: response.response?.statusCode,
                      andErrormsg: &msg)
            
           print("请求结果：\(response)")
           if response.error != nil {
               failureBack(msg)
           }
           else{
               if let jsonObj:[String:Any] = response.value as? [String:Any] {
                   //请求成功
                   if K_API_IS_OK(rs: jsonObj[K_API_RESULT_CODE]) || jsonObj[K_API_RESULT_CODE] as? Int == 200 {
                       successBack(jsonObj[K_API_RESULT_DATA] is NSNull ? Any.self : jsonObj[K_API_RESULT_DATA])
                   }
                   else{
                      failureBack("\(jsonObj[K_API_RESULT_MESSAGE] ?? "请求失败")")
                  }
               }
               else{
                   failureBack(msg)
               }
           }
        }
    }
    
    
    /**!
     * delete 接口请求
     * @para strUrl   String 请求地址
     * @para paras    [String:Any] 请求参数
     * @para successBack  成功回调
     * @para failureBack  失败回调
     */
    func deleteRequestForServerData(strUrl:String,
                                    withParameters paras:[String:Any]?,
                                    AndSuccessBack successBack:@escaping SuccessBlock,
                                    AndFailureBack failureBack:@escaping FailureBlock,
                                    WithisLoading isLoading:Bool = true){
        
        if paras != nil {
            print("请求地址：\(strUrl)?\(paras!.map({ return "\($0.key)=\($0.value)"}).joined(separator: "&"))")
        }
        else{
            print("请求地址：\(strUrl)")
        }
        
        if isLoading == true {
           SVProgressHUD.showLoading()
        }
        
        AF.request(strUrl,
                      method: .delete,
                      parameters: paras)
                .validate()
                .validate(contentType: K_APP_ACCEPTABLE_CONTENTTYPES)
                .responseJSON { response in

           if isLoading == true {
               SVProgressHUD.dismissLoading()
           }
           
           var msg:String? = response.error?.localizedDescription ?? ""
           self.errorHandle(Error: response.error as NSError?,
                       statusCode: response.response?.statusCode,
                      andErrormsg: &msg)
                    
           print("请求结果：\(response)")
           if response.error != nil {
              failureBack(msg)
           }
           else{
               if let jsonObj:[String:Any] = response.value as? [String:Any] {
                   //请求成功
                   if K_API_IS_OK(rs: jsonObj[K_API_RESULT_CODE]) || jsonObj[K_API_RESULT_CODE] as? Int == 200 {
                       successBack(jsonObj[K_API_RESULT_DATA] is NSNull ? Any.self : jsonObj[K_API_RESULT_DATA])
                   }
                   else{
                      failureBack("\(jsonObj[K_API_RESULT_MESSAGE] ?? "请求失败")")
                  }
               }
               else{
                   failureBack(msg)
               }
           }
        }
    }
    
    
    /**!
     * 文件或图片上传
     * @para strUrl String 上传地址
     * @para uploadformDataBack 上传参数设置
     * @para successBack  成功回调
     * @para failureBack  失败回调
     */
    func postImageUploadToServer(strUrl:String,
                                 uploadformDataBack:@escaping(_ fData:MultipartFormData)->(Void),
                                 AndSuccessBack successBack:@escaping SuccessBlock,
                                 AndFailureBack failureBack:@escaping FailureBlock,
                                 WithisLoading isLoading:Bool = true){
        
        print("上传地址：\(strUrl)")

        if isLoading == true {
            SVProgressHUD.showLoading()
        }
        
        AF.upload(multipartFormData: { (_multipartFormData:MultipartFormData) in
            //指定参数
            uploadformDataBack(_multipartFormData)
        }, to: strUrl).responseJSON { _response in
            if isLoading == true {
               SVProgressHUD.dismissLoading()
            }
            
            if _response.error == nil {
                print("上传结果：\(_response)")
                
                var msg:String?
                if let jsonObj:[String:Any] = _response.value as? [String:Any] {
                       //请求成功
                       if K_API_IS_OK(rs: jsonObj[K_API_RESULT_CODE]) || jsonObj[K_API_RESULT_CODE] as? Int == 200 {
                           successBack(jsonObj[K_API_RESULT_DATA] is NSNull ? Any.self : jsonObj[K_API_RESULT_DATA])
                       }
                       else{
                          msg = "\(jsonObj[K_API_RESULT_MESSAGE] ?? "请求失败")"
                          failureBack(msg)
                       }
                }
                else{
                   msg = "请求数据不存在"
                   failureBack("请求数据不存在")
                }
            }
            else {
                failureBack("\(_response.error?.localizedDescription ?? "上传异常")")
            }
        }.validate()
    }
    
    
    //MARK: - 公共请求
    /// 加载省份编号
    /// - Parameters:
    ///   - n: 省份名称
    func loadProvinceAreaIdFor(Name n:String) -> Int {
        let _path = Bundle.main.path(forScaledResource: "address", ofType: "json")
        let _data:Data = try! NSData.init(contentsOfFile: _path!) as Data
        let jsonData = try? JSONSerialization.jsonObject(with: _data, options: [])
        let arrTemp:[[String:Any]]? = jsonData as? [[String:Any]]
        
        guard let dicTemp:[String:Any] = arrTemp?.first(where: { return "\($0["areaName"] ?? "")" == n }) else {
            return 0
        }
        
        return (dicTemp["areaId"] as? Int)!
    }
    
    
    /// 获取app版本更新信息
    /// - Parameters:
    ///   - t: 1客户/供应商 2驻场
    ///   - fb: 加载回调
    func getNewUpdateInfoFor(Type t:Int,andFinishBlock fb:@escaping((_ dicUpdateInfo:[String:Any]?)->(Void))){
        /**
         {
             "code": 0,
             "count": 1,
             "msg": "",
             "data": {
                 "id": 11,
                 "del": false,
                 "last": "2020-09-07 13:59:09",
                 "time": "2020-09-07 13:59:09",
                 "createdBy": "ahri",
                 "modifiedBy": "ahri",
                 "name": "固买云平台",
                 "version": "2.0.6.2",
                 "system": "APPLE",
                 "userType": "VENDOR",
                 "downloadUrl": "https://apps.apple.com/cn/app/id1493876494",
                 "memo": "-新增清除缓存 -优化了部分账号无法登录问题 -app名字变更，由【固买云采购】变更为【固买云平台】 -其他已知问题优化"
             }
         }
         */
        
        let strUrl = String.init(format:"%@basic/member/versionApi/iosLast",K_APP_REQUEST_HOST)
        
        let dicParas:[String:Any] = [
            "userType": t == 2 ? "PM" : "VENDOR",
            //UserModel.k_user_tooken:UserModel.userTooken!
        ]
        
        getRequestForServerData(strUrl: strUrl,
                                withParameters: dicParas,
                                AndSuccessBack: { (responseData:Any?) -> (Void) in
                                    guard let _dicTemp = responseData as? [String:Any] else {
                                        print("没有对应版本更新信息！详见：\(responseData ?? "--")")
                                        return
                                    }
                                    
                                    fb(_dicTemp)
        },
                                AndFailureBack: { (error:String?) -> (Void) in
                                    print("获取app更新信息异常！详见：\(error ?? "--")")
        },
                                WithisLoading: false)
    }
    
    
    /// 获取颜色
    /// - Parameter t: 状态值
    /// - Return (UIColor,UIColor) 字体颜色、背景颜色
    func getColorFor(Title t:String) -> (UIColor,UIColor) {
    
        var fc = "#0079FE"
        var bc = "#E2ECFF"
        
        switch t {
        case "已驳回","退货","驳回","已结束":
            fc = "#FF3B30"
            bc = "#FDE7E6"
            
        case "已关闭","已终止":
            fc = "#FF3B30"
            bc = "#D8F1DD"
            
        case "审核中","询价中","新建中","全部","新建":
            fc = "#0079FE"
            bc = "#E2ECFF"
            
        case "全执行","已通过","审核通过","取消","完成","已开票":
            fc = "#1FC73C"
            bc = "#D8F1DD"
            
        case "未报价","待付款","部分执行","已付款","报价中","未开票","再次报价":
            fc = "#FE9400"
            bc = "#FFF2E0"
            
        case "已报价":
            fc = "#1FC73C"
            bc = "#D8F1DD"
            
        case "已退回":
            fc = "#FF3B30"
            bc = "#D8F1DD"
            
        case "已还价":
            bc = "#E2ECFF"
            fc = "#0079FE"
            
        case "已定标":
            fc = "#FE9400"
            bc = "#FFF2E0"
            
        case "已发货":
            fc = "#22AC38"
            
        default:
            break
        }
        
        return (UIColor.init(hexString: fc)!,UIColor.init(hexString: bc)!)
    }
}
